import React, { Component } from 'react';
import { Table, Select, Input, Button, Dropdown, Menu, Message, Pagination, Tooltip, Confirm } from '@knownsec/react-component';
import { Link, withRouter } from 'react-router-dom';
import s from './style.module.less';
import Loading from '@/components/Loading';
import editeIcon from "@/assets/svg/bianji.svg"
import { getScanResult, getGroupResult, eventBatch, vildVul } from '~/API';
import moment from 'moment';
import { eventSeverityOption, verificationDict, actionDict } from '../columns';
import { filterNull } from '@/utils';
import RuleTable from '@/components/RuleTable'
import CopyText from '@/components/copy'
import EmptyData from '../../../../components/EmptyData';

const info=localStorage.info?JSON.parse(localStorage.info).modules:[]
const eventSeverityDict ={}
for (const item of eventSeverityOption) {
  eventSeverityDict[item.value] = item.label
}
class Vul extends Component {
  constructor(props) {
    super(props);
    
    this.vulColumns = [
      {
        key: 'target_url',
        dataIndex: 'target_url',
        title: '风险地址',
        render: (value, _data) => {
          const name = _data?.detail?.url || '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p><CopyText text={name}/></p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>
                  {name}
              </div>
            </Tooltip>
          )
        },
      },
      {
        key: 'detail',
        dataIndex: 'detail',
        title: '漏洞名称',
        render: (value) => {
          const names = value.name?.zh_cn || '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>漏洞名称：{names}</p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>
                  {names}
              </div>
            </Tooltip>
          )
        },
      },
      {
        key: 'value',
        dataIndex: 'severity_name',
        title: '漏洞等级',
        className: 'xlstablewidth',
        render: (value) =>
          value ? <span className={'risk_' + value}>{eventSeverityDict[value]}</span> : '未知',
      },
      {
        key: 'vuln_type',
        dataIndex: 'vuln_type',
        title: '漏洞类型',
        className: 'xlstablewidth',
        render: (value, data) => {
          const name = data.detail?.vuln_type?.map((item) => item.zh_cn).join('、') || '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>漏洞类型：{name}</p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>
                  {name}
              </div>
            </Tooltip>
          )
        },
      },
      {
        key: 'found_at',
        dataIndex: 'found_at',
        title: '发现时间',
        render: (value, data) => {
          const time = data.detail?.found_at ? moment(data.detail.found_at).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>发现时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>
                  {time}
              </div>
            </Tooltip>
          )
        }
          ,
      },
      {
        key: 'verification',
        dataIndex: 'verification',
        title: '漏洞验证',
        className: 'stablewidth',
        render: (value, data) => { return data?.action?.verification && data.action.verification > 1 && data.action.verification != 3?<a className={s.linkStyle} href={`/#/vul_detail/?id=${data.id}&tid=${this.props.targetId}&type=vul&vild=true&sid=${this.props.sid}&rowSid=${data.task_session_id}`} target='_blank'>{verificationDict[data?.action?.verification]}</a>:<span>{data?.action?.verification ? (
            <span>
              {verificationDict[data?.action?.verification]}
              {data?.action?.verification == 1 ? <Loading color="#2a2b31" /> : null}
            </span>
          ) : (
            '未验证'
          )}</span>}
          
      },
      {
        key: 'user_id',
        dataIndex: 'user_id',
        title: '漏洞状态',
        className: 'xlstablewidth',
        render: (value, data) => (
          <Dropdown overlay={this.menu([data.id])} placement="bottomCenter" arrow>
            <span>
              {actionDict[data?.action?.action] || '待修复'}{' '}
              <img className={s.eidte} src={editeIcon} alt="" />
            </span>
          </Dropdown>
        ),
      },
      {
        key: 'option',
        dataIndex: 'option',
        title: '操作',
        className: 'stablewidth',
        render: (value, _data) => { 
        return   <>
            <Link
              className={s.linkStyle}
              to={{
                pathname: `/vul_detail/`,
                search: `id=${_data.id}&tid=${this.props.targetId}&type=vul&sid=${this.props.sid || ''}&back=${encodeURI(this.state.backUrl)}&rowSid=${_data.task_session_id}`,
              }}
            >
              查看
            </Link>
            {(_data?.action?.verification > 0||!info.includes('vul_verification_task')) ? null : (
              <span
                className={s.linkStyle}
                onClick={() => this.confirmVild(_data.id)}
              >
                验证
              </span>
            )}
          </>
        },
      },
    ];
    const prefilter = new URLSearchParams(props.location.search).get('filter')
    const filter = prefilter?JSON.parse(prefilter) || {}:{}
    const vulQuery = filter.vq || {}
    this.state = {
      selectIds: [],
      refe: false,
      loading: false,
      task_type: [],
      status: [],
      vstatus: [],
      disk_url: '',
      vulName: '',
      datalist: [],
      page: vulQuery.page || 1,
      limit: vulQuery.limit || 10,
      total: 0,
      severity_name: vulQuery.severity_name || '',
      action: vulQuery.action || '',
      verification: vulQuery.verification || '',
      vuln_name: vulQuery.vuln_name || '',
      risk_url: vulQuery.risk_url || '',
      backUrl: ''
    };
  }
  componentDidMount() {
    !info.includes('vul_verification_task') && this.vulColumns.splice(5,1)
    this.getData();
  }
  componentDidUpdate(prevProps) {
    if(prevProps.sid!==this.props.sid){
      this.getData();
    }
  }
  menu(ids) { 
    return (
    <Menu>
      <Menu.Item onClick={()=>this.fixStatus({action: 0},ids)}>
        <span>待修复</span>
      </Menu.Item>
      <Menu.Item onClick={()=>this.fixStatus({action: 1},ids)}>
        <span>已修复</span>
      </Menu.Item>
      <Menu.Item onClick={()=>this.fixStatus({action: 2},ids)}>
        <span>忽略</span>
      </Menu.Item>
    </Menu>
  )};
  vildVulStatus = (id) => {
    var _this = this
    vildVul({'event_id': id}).then(res => {
      if(res.status === 'success'){
        _this.getData()
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }
    })
  };
  onSearchChange = (page) => {
    var _this = this
    if(page.page){
      _this.setState({
        page: page.page,
        limit: page.limit
      }, function(){
        _this.getData()
      })
    }else{
      _this.setState({
        page: 1,
        limit: 10
      }, function(){
        _this.getData()
      })
    }
  }
  confirmVild(a){
    var _this = this
    Confirm({
      pro: true,
      title: '确认提示',
      message: <div className="confirmbox">确认要验证该地址吗？</div>,
      onconfirm: () => {
        // _this.fixStatus(a, b)
        _this.vildVulStatus(a)
      },
      oncancel: () => {},
    });
  }
  fixStatus(params,ids){
    // ,verification: 0
    // action: a
    var _this = this
    const data = Object.assign({event_ids: ids}, params)
    eventBatch(data).then(res => {
      if(res.status === 'success'){
        _this.getData()
        _this.setState({refe: !_this.state.refe, selectIds: []})
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }
    })
  }
  getData() {
    if (this.props?.fetchable === 'fail') return false
    const querydata = {
      page: this.state.page,
      limit: this.state.limit,
      severity_name: this.state.severity_name,
      verification: this.state.verification,
      action: this.state.action,
      risk_url: this.state.risk_url,
      vuln_name: this.state.vuln_name
    } 

    const f = JSON.stringify(filterNull({locKeyNum: '漏洞', vq: querydata}))
    this.setState({backUrl: f, selectIds: [], refe: !this.state.refe })
    this.props.history.replace(`/dashboard/?id=${this.props.targetId}&type=${this.props.type || ''}&sid=${this.props.sid || ''}&filter=${encodeURI(f)}`)
    
    this.setState({ loading: true });
    this.getDataFun(querydata)
  }
  getDataFun(querydata){
    let API = null
    if(this.props.sid){
      API = getGroupResult({ id: this.props.sid, data: querydata })
    }else{
      API = getScanResult({ id: this.props.targetId, type: 'vul', data: querydata })
    }
    API.then((res) => {
      if (res.status === 'success') {
        const data = res.data?.data.events;
        let vulStatus = false;
        data.map((item) => {
          item.id = item.event_id;
          if(item.action?.verification===1){
            vulStatus=true
          }
          return item
         });
        this.setState({ datalist: data, total: res.data.total, loading: false });
        if(vulStatus&&this.props.history.location.pathname==='/dashboard/'){
          setTimeout(() => {
            this.getDataFun(querydata)
          },10*1000)
        }
      } else {
        this.setState({ datalist: [], total: 0, loading: false });
      }
    }).catch(_ => {
        this.setState({ datalist: [], total: 0, loading: false });
    });
  }
  setVal(label, val, type) {
    let callback,obj
    obj = {[label]: val}
    if(type){
      obj = {[label]: val,page: 1, limit: 10}
      callback = function(){
        this.getData()
      }
    }
    this.setState(obj,callback);
  }
  setSelTable(e) {
    this.setVal('selectIds', e);
  }
  generateOption(arr){
    let res = arr.map((item,index) => { return {label: item, value: index}})
    return res
  }
  renderSearch() {
    return (
      <>
        <Select
          option={eventSeverityOption}
          pro
          placeholder="请选择漏洞等级"
          className="selectItem"
          clearable
          value={this.state.severity_name}
          onChange={({ selectedItem }) => {
            const params = selectedItem[0] ? selectedItem[0].value : ''
            this.setVal('severity_name', [params], 'getData');
          }}
        />
        <Select
          option={this.generateOption(actionDict)}
          pro
          placeholder="请选择漏洞状态"
          className="selectItem"
          clearable
          value={this.state.action}
          onChange={({ selectedItem }) => {
            const params = selectedItem[0] ? selectedItem[0].value : ''
            this.setVal('action', [params], 'getData');
          }}
        />
        <Select
          option={this.generateOption(verificationDict)}
          pro
          placeholder="请选择漏洞验证状态"
          className="selectItem"
          clearable
          value={this.state.verification}
          onChange={({ selectedItem }) => {
            const params = selectedItem[0] ? selectedItem[0].value : ''
            this.setVal('verification', [params], 'getData');
          }}
        />
        <Input
          pro
          placeholder="搜索风险地址"
          value={this.state.risk_url}
          autoComplete={'off'}
          search
          className="search-button"
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('risk_url', value.value)
            if (!value.e) {
              this.onSearchChange({val:'risk_url'})
            }
          }}
        ></Input>
        <Input
          pro
          placeholder="搜索漏洞名称"
          value={this.state.vuln_name}
          autoComplete={'off'}
          search
          className="search-button last"
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('vuln_name', value.value)
            if (!value.e) {
              this.onSearchChange({val:'vuln_name'})
            }
          }}
        ></Input>
      </>
    );
  }
  render() {
    return (
      <div className={s.wangsecurity}>
        <div className="searchBox">
          <div className="searchLeft" style={{marginRight: 16}}>
            <Dropdown disabled={!this.state.selectIds.length} overlay={this.menu(this.state.selectIds)} placement="bottomCenter" arrow>
              <Button pro type="default">批量操作</Button>
            </Dropdown>
          </div>
          <div className="searchRight">{this.renderSearch()}</div>
        </div>
        
        {info.includes('vul')? 
            <Table
              selectable
              refre={this.state.refe}
              tableLoading={this.state.loading}
              loadingLabel=""
              className={this.state.selectIds.length ? 'half-select' : ''}
              columns={this.vulColumns}
              data={this.state.datalist}
              empty={this.props?.fetchable === 'fail' && <EmptyData text='未开启该监测项'/>}
              getCheckedList={(e) => {
                this.setSelTable(e);
              }}
            ></Table>:
            <RuleTable selectable columns={this.vulColumns} data={this.state.datalist}></RuleTable>
        }
        {(info.includes('vul') && this.state.total > 10) && <Pagination
            className={s.pagination}
            current={this.state.page}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={this.state.limit}
            pageSizeOptions={['10', '20', '50']}
            total={this.state.total}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              this.onSearchChange({ page, limit: size });
            }}
          />}
      </div>
    );
  }
}

export default withRouter(Vul);
